package com.imooc.service.impl;

import com.imooc.enums.ErrorMsg;
import com.imooc.exception.CustomException;
import com.imooc.mapper.UserAddressMapper;
import com.imooc.pojo.UserAddress;
import com.imooc.pojo.bo.AddressBO;
import com.imooc.service.AddressService;
import com.imooc.utils.CommonJsonResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.n3r.idworker.Sid;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @Author: 逸尘风清
 * @Date: 2021/5/6
 * @Time: 22:08
 * 描述：
 */
@Service
@Slf4j
public class AddressServiceImpl implements AddressService {
    @Resource
    private UserAddressMapper userAddressMapper;
    @Resource
    private Sid sid;

    @Override
    public List<UserAddress> getAddress(String userId) {
        Example example = new Example(UserAddress.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userId", userId);
        List<UserAddress> userAddressList = userAddressMapper.selectByExample(example);
        return userAddressList;
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public UserAddress addOrUpdateAddress(AddressBO addressBO) {
        // 为空表示添加，否则表示更新
        if (StringUtils.isBlank(addressBO.getAddressId())) {
            // 复制属性
            UserAddress userAddress = new UserAddress();
            BeanUtils.copyProperties(addressBO,userAddress);
            // 生成唯一ID
            userAddress.setId(sid.nextShort());
            // 查询数据库中是否有地址，如果有则直接添加，如果没有则需要将这个地址改成默认地址
            Example example = new Example(UserAddress.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("userId", userAddress.getUserId());
            List<UserAddress> userAddressList = userAddressMapper.selectByExample(example);

            if (!CollectionUtils.isEmpty(userAddressList)) {
                userAddress.setIsDefault(0);
            } else {
                userAddress.setIsDefault(1);
            }
            userAddress.setCreatedTime(new Date());
            userAddress.setUpdatedTime(new Date());

            /* 模拟异常 */
            // try {
            //     int i = 1 / 0;
            // } catch (Exception e) {
            //     throw new CustomException(ErrorMsg.ERROR_INSERT_DATA);
            // }

            int count = userAddressMapper.insert(userAddress);

            if (count == 0) {
                throw new CustomException(ErrorMsg.ERROR_INSERT_DATA);
            }
            return userAddress;
        } else {
            //表示更新
            UserAddress userAddress = userAddressMapper.selectByPrimaryKey(addressBO.getAddressId());
            BeanUtils.copyProperties(addressBO,userAddress);
            userAddress.setUpdatedTime(new Date());
            userAddressMapper.updateByPrimaryKey(userAddress);
            return userAddress;
        }
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public CommonJsonResult delAddress(String userId, String addressId) {
        Example example = new Example(UserAddress.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userId", userId);
        criteria.andEqualTo("id", addressId);
        userAddressMapper.deleteByExample(example);
        return CommonJsonResult.ok();
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public CommonJsonResult setDefaultAddress(String userId, String addressId) {
        Example example = new Example(UserAddress.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userId", userId);
        criteria.andEqualTo("id", addressId);
        UserAddress userAddress = userAddressMapper.selectOneByExample(example);
        if (userAddress == null) {
            log.warn("查询不到相关地址信息，用户ID为：{},收货地址ID为：{}",userId,addressId);
            return CommonJsonResult.errorMsg("查询不到地址信息");
        }
        // 查找是否有默认地址
        Example example1 = new Example(UserAddress.class);
        Example.Criteria criteria1 = example1.createCriteria();
        criteria1.andEqualTo("userId", userId);
        criteria1.andEqualTo("isDefault", 1);
        UserAddress userAddress1 = userAddressMapper.selectOneByExample(example1);
        if (userAddress1 != null) { // 有默认地址判断id是否一致
            if (addressId.equals(userAddress1.getId())) {  // 一致不需要进行任何操作
                return CommonJsonResult.errorMsg(ErrorMsg.IS_ALREADY_DEFAULT_ADDRESS);
            } else {  // 不相等，需要先把之前的默认地址更改成普通的
                userAddress1.setIsDefault(0);
                userAddressMapper.updateByPrimaryKey(userAddress1);
                userAddress.setIsDefault(1);
                userAddressMapper.updateByPrimaryKey(userAddress);
            }
        } else {
            userAddress.setIsDefault(1);
            userAddressMapper.updateByPrimaryKey(userAddress);
        }

        return CommonJsonResult.ok();
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public UserAddress getSingleAddressByUserIdAndAddressId(String userId, String addressId) {
        UserAddress singleAddress = new UserAddress();
        singleAddress.setUserId(userId);
        singleAddress.setId(addressId);
        return userAddressMapper.selectOne(singleAddress);
    }
}
